package edu.cmu.cs.cs214.hw9.client.controllers.eventhandlers;

import javax.swing.SwingWorker;

import edu.cmu.cs.cs214.hw9.client.controllers.BackendCacheAdapter;
import edu.cmu.cs.cs214.hw9.client.controllers.SessionController;
import edu.cmu.cs.cs214.hw9.datatypes.User;

/**
 * Let the currently logged in user defriend another user
 */
public class RemoveFriendHandler extends SessionEventHandler {
	/**
	 * Run the de-friend request in a separate thread to prevent swing from freezing.
	 */
	private class RemoveFriendWorker extends SwingWorker<Boolean, Void> {
		private BackendCacheAdapter model;
		private User currentUser;
		private User target;
		
		/**
		 * Constructs a new de-friend request. Will remove the target as a friend from
		 * the currently logged in user's friends list.
		 * 
		 * @param target Friend to remove.
		 */
		public RemoveFriendWorker(User target) {
			this.target = target;
			currentUser = controller.getCurrentUser();
			model = controller.getModel();
		}
		
		/**
		 * Removes the friend from the logged in user's friends list.
		 * 
		 * @return true if successful; false otherwise.
		 */
		public Boolean doInBackground() {
			return model.removeFriend(currentUser, target);
		}
	};
	
	/**
	 * Set the current session controller to the provided controller.
	 * 
	 * @param controller Controller to associate with this event handler.
	 */
	public RemoveFriendHandler(SessionController controller) { super(controller); }
	
	/**
	 * Create the de-friend request and run it in an outside thread.
	 * 
	 * @param param Friend to remove/de-friend.
	 */
	public void handleEvent(Object param) {
		RemoveFriendWorker removeFriendWorker = new RemoveFriendWorker((User) param);
		removeFriendWorker.execute();
	}
}
